var url = "http://47.105.118.98:9013";
var ins1;
var table;
var form;
var upload;
var option = {
    elem: "#demo",
    id: "demo",
    url: url + "/document/querybyuseridfilename",
    method: "post",
    headers: {
        token: localStorage.getItem("token"),
    },
    request: {
        pageName: "currentPage", //页码的参数名称，默认：page
        limitName: "size", //每页数据量的参数名，默认：limit
    },
    where: {
        userid: localStorage.getItem("id"),
        filename: ""
    },

    parseData: function (res) {
        console.log(res);
        return {
            code: "0",
            data: setData(res.data.records),
            count: res.data.total,
        };

    },
    height: "full-140",
    text: {
        none: "暂无数据", //默认：无数据。注：该属性为 layui 2.2.5 开始新增
    },
    page: true,
    cols: [
        [{
            type: "checkbox",
            width: 80,
            fixed: "left",
        },
        {
            field: "xvhao",
            type: "numbers",
            title: "序号",
            align: "center",
            width: 80,
        },
        {
            field: "createtime",
            title: "创建时间",
            align: "center",
            width: 180,
            sort: true,
            templet: function (d) {
                var t1 = d.createtime
                return util.toDateString(t1);
            }
        },
        {
            field: "filename",
            title: "文件名",
            align: "center",
        },
        {
            field: "geshi",
            title: "格式",
            align: "center",
            width: 100
        },
        {
            fixed: "right",
            width: 180,
            title: "操作",
            toolbar: "#newsListBar",
            align: "center",
        },
        ],
    ],
};
function setData(data) {

    data.forEach(item => {
        //  item.createtime = layui.util.toDateString(data.createtime * 1000, 'yyyy-MM-dd HH:mm:ss')
        var s = item.filepath.split("/")
        var n = s[3].split("_")
        var m = s[3].split(".")
        //   item.filename = n[0]
        item.geshi = m[1]
    });
    return data
}

layui.use(["table", "form", "jquery", "upload", "laydate"], function () {
    table = layui.table;
    form = layui.form;
    upload = layui.upload;
    $ = layui.jquery;
    ins1 = table.render(option);
    laydate = layui.laydate;
    var tableIns = table.render(option);
    util = layui.util
    laydate.render({
        elem: '#date',
        trigger: 'click'
    });



    // 根据选中行删除选中内容
    $("#delete_Btn").on("click", function () {
        layer.confirm('确定删除选中内容？', {
            btn: ['确定', '取消']
        }, function () {
            var checkStatus = table.checkStatus('demo'); //即为基础参数 id 对应的值
            var data1 = '';
            checkStatus.data.forEach((item) => {
                data1 += item.id + ',';
            });
            data1 = data1.substr(0, data1.length - 1)
            var data2 = data1.split(",")
            //  console.log(data1)
            //  console.log(data2)
            if (data2.length !== 0) {
                for (var i = 0; i < data2.length; i++) {
                    $.ajax({
                        url: url + "/document/deletebyuserid",
                        method: "post",
                        data: {
                            id: data2[i]
                        },
                        headers: {
                            token: localStorage.getItem('token')
                        },
                        success: function (data) {
                            // console.log(data)
                            if (data.code === 200) {
                                tableIns.reload();
                                layer.msg('删除成功！')

                            } else {
                                layer.msg("请先选择需要删除的内容！")
                            }

                        },
                        error: function (err) {
                            layer.msg('删除失败！')
                        }
                    })
                }
            } else {
                layer.msg("请先选择需要删除的内容！", {
                    icon: 2
                });
            }
        }, function () {
            console.log("取消")
        })

    })
    // 上传弹窗接口
    $("#shangchuan").on("click", function uploadFile() {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                area: ["600px", "450px"],
                title: "上传文件",
                content: $("#file_upload_div")
            })
        });
    }),
        layui.use(['upload', 'element', 'layer'], function () {
            laydate.render({
                elem: '#date',
                trigger: 'click'
            });
            var element = layui.element, layer = layui.layer;
            var timer;//定义一个计时器
            var upload = layui.upload;
            let cookies = document.cookie.split(',');
            let pattern = /csrftoken=(.*)/m;
            let csrf;
            for (let j = 0; j < cookies.length; j++) {
                if (pattern.test(cookies[j])) {
                    csrf = pattern.exec(cookies[j])[1];
                }
            }
            //执行实
            var uploadInst = upload.render({
                elem: '#test10' //绑定元素
                ,
                headers: {
                    "X-CSRFToken": csrf
                },
                before: function (obj) { //obj参数包含的信息，跟choose回调完全一致
                    layer.load(); //上传loading
                    this.data = {
                        fileName: document.getElementById("file_name").value
                    }
                    var n = 0;
                    timer = setInterval(function () {//按照时间随机生成一个小于95的进度，具体数值可以自己调整
                        n = n + Math.random() * 10 | 0;
                        if (n > 95) {
                            n = 95;
                            clearInterval(timer);
                        }
                        element.progress('demo', n + '%');
                    }, 50 + Math.random() * 100);

                }

                , done: function (res, index, upload) {
                    //       res.data.fileName = document.getElementById("file_name").value
                    console.log(res)
                    clearInterval(timer);
                    element.progress('demo', '100%');//一成功就把进度条置为100%
                    layer.closeAll();
                    element.progress('demo', '0%');//一成功就把进度条置为100%
                    layer.msg('上传成功');
                    document.getElementById("file_name").value = ""
                    tableIns.reload();
                    // delete this.files[index]
                }, error: function (index, upload) {
                    element.progress('demo', '0%'); layer.closeAll(); //关闭所有层
                    layer.msg('上传失败');
                }
                , accept: "file"
                //, exts: 'xls|xlsx|csv|zip|pdf|doc|docx|png|jpeg|jpg|gif|txt'// 设置允许上传的格式
                , auto: false
                , bindAction: "#upload"
                , url: url + '/document/upfile' //上传接口
                , headers: {
                    token: localStorage.getItem("token"),
                }
                //   , data: { fileName: document.getElementById("file_name").value }
                , method: "post"
                , choose: function (obj) {
                    //    var files = this.files = obj.pushFile();
                    obj.preview(function (index, file, result) {
                        document.getElementById("file_name").value = file.name;
                        //      var files = obj.pushFile()
                        //    console.log(files[index].name);
                        // = files[index].name
                    })
                }
            });
        });
    before: function uploadFile() {
    }
    $('.sousuo1').keydown(function (e) {
        if (e.keyCode === 13) {
            $("#chaxun").trigger("click");
            return false
        }
    });
    $("#chaxun").click(function () {
        //重新加载表格
        var keywords = document.getElementById("sousuo").value
        console.log(keywords)
        table.reload('demo', {
            where: {
                filename: keywords
            },
            page: {
                curr: 1 //重新从第 1 页开始
            }
        })
    })
    //列表操作：下载，编辑与删除
    table.on('tool(demo)', function (obj) {
        var layEvent = obj.event,
            data1 = obj.data;
        if (layEvent === 'xiazai') {
            // layer.confirm('确定下载  ' + data1.filename + '  ？', {
            //     btn: ['确定', '取消']
            // }, function () {      
            var path = url + data1.filepath
            var x = new XMLHttpRequest();
            x.open("GET", path, true);
            x.responseType = 'blob';
            x.onload = function (e) {
                var url1 = window.URL.createObjectURL(x.response)
                var aa = document.createElement("a");
                aa.href = url1
                aa.download = data1.filename
                aa.style.display = "none";
                document.body.appendChild(aa);
                aa.click();
                document.body.removeChild(aa)
            }
            x.send()
            // }, function () {
            //     console.log("取消")
            // })
            //     var s = data1.filepath.split("/");

        }
        else {
            layer.confirm('确定删除  ' + data1.filename + '  ？', {
                btn: ['确定', '取消']
            }, function () {
                // console.log("确定")
                console.log(data1);
                console.log(data1.id);
                $.ajax({
                    url: url + "/document/deletebyuserid",
                    method: "post",
                    data: {
                        id: data1.id,
                        // keywords: "",
                    },
                    headers: {
                        token: localStorage.getItem('token')
                    },
                    success: function (data) {
                        //      console.log(data)
                        if (data.code === 200) {
                            tableIns.reload();
                            layer.msg('删除成功！')

                        } else {
                            layer.msg(data.msg)
                        }

                    },
                    error: function (err) {
                        layer.msg('删除失败！')
                    }
                })
            }, function () {
                console.log("取消")
            })
        }
    })


});


